<script lang="ts">
  import { FOLLOW_STATUS } from '@/enum/dynamic.enum';
  import { computed, defineComponent, ref } from '@vue/composition-api';
  import FollowButton from '@/components/business/follow-button.vue';
  import DynamicList from '@/components/business/dynamic-list.vue';
  import { getPersonalMessage, PersonalMessageDto, watchUser } from '@/api/user';
  import { onLoad, onPullDownRefresh, onReachBottom } from '@/hooks/uniapp-composition-hooks';
  import { Message } from '@/libs';
  import { Dynamic, getPersonalDynamicList } from '@/api/dynamic';
  import OtoButton from '@/components/common/oto-button.vue';
  import { ROUTER_PATHS, useRouter } from '@/constants/router';
  import { useStore } from '@/store';
  import { UserModule } from '@/store/modules/user.module';

  export enum LoadStatusEnum {
    LODING = 'loading',
    LOAD_MORE = 'loadmore',
    NO_MORE = 'nomore',
    LOADING_ERROR = 'loadingErro'
  }

  export type PageData = {
    loadStatus: LoadStatusEnum;
    current: number;
    size: number;
    total: number;
    lastId: number;
    type: number;
  };

  function wait(time = 150) {
    return new Promise((resolve) => {
      const id = setTimeout(() => {
        resolve(id);
      }, time);
    });
  }

  export default defineComponent({
    components: {
      FollowButton,
      DynamicList,
      OtoButton
    },
    setup(_) {
      const router = useRouter();
      const userModule = useStore(UserModule);

      const userId = ref(0);
      const personalMessage = ref<PersonalMessageDto>({
        id: 0,
        avatarUrl: '',
        nickName: '',
        dynamicLoveCount: 0,
        followCount: 0,
        fansCount: 0,
        followStatus: FOLLOW_STATUS.NOT_FOLLOW
      });
      const isSelf = computed(() => {
        return userModule.userInfo.id === personalMessage.value?.id;
      });

      const personalDataItemList = ref([
        {
          title: '获赞',
          value: 'dynamicLoveCount'
        },
        {
          title: '关注',
          value: 'followCount'
        },
        {
          title: '粉丝',
          value: 'fansCount'
        }
      ]);
      const pageData = ref<PageData>({
        loadStatus: LoadStatusEnum.LOAD_MORE,
        current: 1,
        size: 10,
        total: 0,
        lastId: 0,
        type: 0
      });

      const pages = computed(() => {
        return Math.ceil(pageData.value.total / pageData.value.size);
      });

      function changeStatus(status: FOLLOW_STATUS) {
        console.log(status);
        watchUser(userId.value)
          .then((res) => {
            console.log(res);
            personalMessage.value.followStatus = status;
            if (status === FOLLOW_STATUS.FOLLOW) {
              Message.success('关注成功');
            } else {
              Message.success('取消关注成功');
            }
          })
          .catch((err) => {
            console.error(err);
          });
      }

      async function getDynamicListForPage(loadState = false) {
        // 防止多次触发加载
        if (pageData.value.loadStatus === LoadStatusEnum.LODING) return;

        // 全部刷新
        if (loadState) {
          return;
        }
        const { current, size, lastId } = pageData.value;

        // 没有更多了
        if (pages.value > 0 && current > pages.value) {
          pageData.value.loadStatus = LoadStatusEnum.NO_MORE;
          return;
        }
        // 进行加载
        pageData.value.loadStatus = LoadStatusEnum.LODING;

        await wait(350);

        getPersonalDynamicList(userId.value, current, size, lastId)
          .then((res) => {
            const data = res.data;
            if (!data.list) {
              pageData.value.loadStatus = LoadStatusEnum.NO_MORE;
            }
            if (!pageData.value.lastId && data.list.length > 0) {
              pageData.value.lastId = data.list[0].id;
            }

            pageData.value.total = data.total;

            // 判断是否时翻页
            if (current === 1) {
              list.value = data.list;

              if (data.list.length === 0) {
                pageData.value.loadStatus = LoadStatusEnum.NO_MORE;
                pageData.value.current += 1; // 页数加一
                return;
              }
            } else {
              data.list.forEach((item) => {
                list.value.push(item);
              });
            }

            // pageData.value.size = data.size; // 应该按照前端的size来
            if (current < pages.value) {
              // 加载更多
              pageData.value.loadStatus = LoadStatusEnum.LOAD_MORE;
              pageData.value.current += 1; // 页数加一
            } else {
              pageData.value.loadStatus = LoadStatusEnum.NO_MORE;
            }
          })
          .catch((err) => {
            // 出错了
            pageData.value.loadStatus = LoadStatusEnum.LOADING_ERROR;
            console.log('err', err);
          });
      }

      const list = ref<Dynamic[]>([]);

      function loadMore() {
        console.log('加载更多');
        if (pageData.value.loadStatus === LoadStatusEnum.NO_MORE) return;
        getDynamicListForPage();
      }

      function refreshAll() {
        // 初始化pageData
        pageData.value = {
          current: 1,
          size: 10,
          total: 0,
          loadStatus: LoadStatusEnum.LOAD_MORE,
          lastId: 0,
          type: pageData.value.type
        };
        // 清空列表数据
        list.value = [];
      }

      function toPrivateChat() {
        router.navigateTo({
          url: ROUTER_PATHS.PRIVATE_CHAT,
          params: {
            to: userId.value
          }
        });
      }

      onLoad((options) => {
        if (options) {
          userId.value = Number(options.id);
          getPersonalMessage(userId.value)
            .then((res) => {
              personalMessage.value = res.data;
            })
            .catch((err) => {
              console.log(err);
            });
          getDynamicListForPage();
        }
      });

      onReachBottom(() => {
        console.log('触底');
        loadMore();
      });

      onPullDownRefresh(async () => {
        uni.showLoading({
          mask: true,
          title: '刷新中～'
        });
        refreshAll();
        try {
          await getDynamicListForPage();
        } catch (error) {
          console.error(error);
        }
        uni.hideLoading();
        uni.hideNavigationBarLoading();
        uni.stopPullDownRefresh();
        console.log('触发了');
      });

      return {
        isSelf,
        userId,
        list,
        pageData,
        pages,
        personalMessage,
        personalDataItemList,
        changeStatus,
        loadMore,
        toPrivateChat
      };
    }
  });
</script>

<template>
  <view class="personal">
    <view class="background"> </view>
    <view class="body">
      <view class="user-message">
        <view class="user-message-body">
          <view class="user-avatar">
            <view class="user-avatar-body"></view>
            <image class="user-avatar-image" :src="personalMessage.avatarUrl" />
          </view>
          <view class="user-data">
            <view class="user-name">{{ personalMessage.nickName }}</view>
            <!-- <veiw class="user-active">个人活跃度：1000</veiw> -->
            <view class="user-class">别看我只是一只羊～</view>
          </view>
        </view>
        <view class="private-message" v-if="!isSelf">
          <oto-button
            @click.stop="toPrivateChat"
            :customStyle="{
              fontSize: '30rpx',
              background: '#77c545'
            }"
          >
            私信他/她
          </oto-button>
        </view>
      </view>
      <view class="personal-data">
        <template v-for="(item, index) in personalDataItemList">
          <view class="personal-data-item" :key="index">
            <view class="item-title"> {{ item.title }}</view>
            <view class="item-text">{{ personalMessage[item.value] }}</view>
          </view>
        </template>
        <view class="follow" v-if="!isSelf">
          <follow-button :status="personalMessage.followStatus" @change="changeStatus" />
        </view>
      </view>
      <view class="dynamic-list">
        <dynamic-list :list="list" />
      </view>
    </view>
    <view class="loading">
      <u-loadmore bg-color="rgb(240, 240, 240)" :status="pageData.loadStatus" @loadmore="loadMore"></u-loadmore>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  .personal {
    .background {
      height: 360rpx;
      /* 渐变1 */

      background: linear-gradient(90deg, #5d5fef 0%, #947cc8 100%);
    }

    .body {
      margin-top: -216rpx;
      background: #ffffff;
      border-radius: 0px 60rpx 0px 0px;
      min-height: 400rpx;
      padding: 0 54rpx 0 54rpx;

      .user-message {
        position: relative;
        height: 100rpx;

        &-body {
          position: absolute;
          display: flex;
          top: -100rpx;
        }

        .private-message {
          width: 160rpx;
          height: 60rpx;
          position: absolute;
          top: 20rpx;
          right: 0;
        }

        .user-avatar {
          width: 200rpx;
          height: 200rpx;
          border-radius: 50%;
          position: relative;
          margin-left: -24rpx;

          &-body {
            position: absolute;
            z-index: 2;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200rpx;
            height: 200rpx;
            /* 渐变1 */

            background: linear-gradient(90deg, #5d5fef 0%, #947cc8 100%);
            opacity: 0.1;
            filter: blur(6rpx);
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
          }

          &-image {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 3;
            width: 160rpx;
            height: 160rpx;
            background-color: aquamarine;
            border-radius: 50%;
          }
        }

        .user-data {
          flex: 1;
          font-family: 'PingFang SC';
          font-style: normal;
          font-weight: 600;
          font-size: 42rpx;
          line-height: 59rpx;
          color: #ffffff;
          margin-left: 16rpx;

          .user-name {
            margin-top: 45rpx;
          }

          .user-active {
            /* 说明文字（小） */

            font-family: 'PingFang SC';
            font-style: normal;
            font-weight: 400;
            font-size: 20rpx;
            line-height: 28rpx;
            /* identical to box height */

            /* 点缀色 */

            color: #ff9900;
          }

          .user-class {
            font-family: 'PingFang SC';
            font-style: normal;
            font-weight: 500;
            font-size: 26rpx;
            line-height: 36rpx;
            text-align: center;
            color: #666666;
            margin-top: 16rpx;
          }
        }
      }

      .personal-data {
        margin-top: 24rpx;
        margin-bottom: 24rpx;
        display: flex;
        position: relative;

        &-item {
          &:not(:first-child) {
            margin-left: 120rpx;
          }
          .item-title {
            font-family: 'PingFang SC';
            font-style: normal;
            font-weight: 500;
            font-size: 22rpx;
            line-height: 31rpx;
            /* identical to box height */

            text-align: center;

            color: #666666;
          }

          .item-text {
            margin-top: 8rpx;
            font-family: 'DIN Alternate';
            font-style: normal;
            font-weight: 700;
            font-size: 32rpx;
            line-height: 37rpx;
            text-align: center;

            color: #333333;
          }
        }

        .follow {
          position: absolute;
          right: 54rpx;
          top: 50%;
          transform: translateY(-50%);
        }
      }

      .dynamic-list {
      }
    }

    .loading {
      padding-bottom: 60rpx;
    }
  }
</style>
